﻿using Application.Common.Interfaces;
using FluentValidation;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Users.Commands.Delete;

/// <summary>
/// 校验修改角色信息
/// </summary>
public class DeletUserCommandValidator : AbstractValidator<DeleteUserCommand>
{
    private readonly IApplicationDbContext _context;
    public DeletUserCommandValidator(IApplicationDbContext context)
    {
        _context = context;

        RuleFor(x => x.UserIds).MustAsync(UserExistsAsync).WithMessage("非法数据！");

        RuleFor(x => x.UserIds).MustAsync(AllowedDeleteUserAsync).WithMessage("不允许删除系统超级管理员账号！");
    }

    private async Task<bool> UserExistsAsync(List<long> userIds, CancellationToken cancellationToken)
    {
        var existingUsers = await _context.Users.Where(x => userIds.Contains(x.Id)).ToListAsync();

        if (existingUsers == null || userIds.Count != existingUsers.Count)
        {
            return false;
        }

        // 用户ID都在数据库中存在且数量一致
        bool allIdsMatched = existingUsers.Select(r => r.Id).All(id => userIds.Contains(id));

        return allIdsMatched;
    }

    private async Task<bool> AllowedDeleteUserAsync(List<long> userIds, CancellationToken cancellationToken)
    {
        var existingUsers = await _context.Users.Where(x => userIds.Contains(x.Id)).ToListAsync();

        if (existingUsers == null || userIds.Count != existingUsers.Count)
        {
            return false;
        }

        foreach (var item in existingUsers)
        {
            if (item.IsSystemAccount.HasValue)
            {
                if (item.IsSystemAccount.Value)
                    return false;
            } 
        }

        // 用户ID都在数据库中存在且数量一致
        bool allIdsMatched = existingUsers.Select(r => r.Id).All(id => userIds.Contains(id));

        return allIdsMatched;
    }
}